//ex8-15.c recv
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include"shm_com.h"

int main(int argc,char* *argv){
	int running = 1;
	void * share_memory = (void*)0;
	struct shared_use_st *shared_stuff;
	int shmid;
	char buffer[BUFSIZ];
	
	//create
	shmid = shmget( (key_t)1234 , sizeof(struct shared_use_st) , 0666|IPC_CREAT);
		
	if(shmid == -1){
		fprintf(stderr,"Create ShareMem Error: %s \n\a", strerror(errno));
		exit(1);		
	}
		
	share_memory = shmat(shmid, (void *)0 , 0);
	if(share_memory == (void *)-1){
		fprintf(stderr,"shmat Error: %s \n\a", strerror(errno));
		exit(EXIT_FAILURE);	
	}

	printf("Memory attached at %x \n",(int)share_memory);
	
	shared_stuff = (struct shared_use_st *)share_memory;

	while(running){
		while(shared_stuff->written_by_you ==1){
			sleep(1);
			printf("wait for Client ...");
		}
		printf("Enter some text :\n" );
		fgets(buffer ,BUFSIZ, stdin );
		strncpy(shared_stuff->some_text, buffer,BUFSIZ);

		shared_stuff->written_by_you =1;
		
		if( strncmp (buffer,"end",3 ) ==0){
			running = 0;
		}	
	}

	if( shmdt(share_memory) == -1 ){
		fprintf(stderr,"shmdt Error: %s \n\a", strerror(errno));
		exit(EXIT_FAILURE);			
	}
	
	exit(EXIT_SUCCESS);	
}

